package com.quarkus.resource;

import io.smallrye.jwt.auth.principal.JWTParser;
import io.smallrye.jwt.auth.principal.ParseException;
import io.smallrye.jwt.build.Jwt;
import io.smallrye.mutiny.Uni;
import org.eclipse.microprofile.jwt.JsonWebToken;

import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.ws.rs.CookieParam;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.NewCookie;
import javax.ws.rs.core.Response;

/**
 * @version v1.0
 * @Description: TODO(一句话描述该类的功能)
 * @Author: TongRui乀
 * @Date: 2021/3/7 2:34 下午
 */
@Path("parser")
@RequestScoped
public class JwtParserResource {

    @Inject
    JWTParser jwtParser;

    @Inject
    JsonWebToken jsonWebToken;

    private String secret = "AyM1SysPpbyDfgZld3umj1qzKObwVMko";

    @GET
    @Path("{name}")
    @Produces("text/plain")
    public Response generateJwt(@PathParam("name") String name){
        String sign = Jwt
                .upn(name)
                .signWithSecret(secret);
        System.out.println(sign);
        return Response.ok("Success").cookie(new NewCookie("jwt", sign)).build();
    }


    @GET
    @Path("verify")
    @Produces("text/plain")
    public Response verify(@CookieParam("jwt") String token) throws ParseException {
        return Response.ok(jwtParser.verify(token, secret).getClaim("upn")).build();
    }

    @GET
    @Produces("text/plain")
    public Response getUserName(@CookieParam("jwt") String jwtCookie) throws ParseException {
        Response response = null;
        if (jwtCookie == null) {
            // Create a JWT token signed using the 'HS256' algorithm
            String newJwtCookie = Jwt.upn("Alice").signWithSecret(secret);
            // or create a JWT token encrypted using the 'A256KW' algorithm
            // Jwt.upn("alice").encryptWithSecret(secret);
            return Response.ok("Alice").cookie(new NewCookie("jwt", newJwtCookie)).build();
        } else {
            // All mp.jwt and smallrye.jwt properties are still effective, only the verification key is customized.
            JsonWebToken jwt = jwtParser.verify(jwtCookie, secret);
            // or jwt = parser.decrypt(jwtCookie, secret);
            return Response.ok(jwt.getName()).build();
        }
    }

}
